package com.itjiange.servlet;

import com.itjiange.utils.CustomConstants;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

/**
 * 上传文件列表
 *
 * @author ItJiange
 * @date 2023/10/18
 */
@WebServlet("/upload-files")
@MultipartConfig
public class FileListUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // req.getPart("file");// 获取上传的一个文件
        req.setCharacterEncoding("UTf-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        Collection<Part> parts = req.getParts();
        String downloadLinks = "";
        String message = "";
        for (Part part : parts) {
            String type = part.getContentType();
            String name = part.getSubmittedFileName();
            if (!CustomConstants.ALLOW_TYPES.contains(type)) {
                message += "<p>" + name + "上传失败，文件格式不支持</p>";
                return;
            }
            String fileName = CustomConstants.ROOT_PATH + File.separator + name;
            File file = new File(fileName);
            // 如果目录不存在就去创建目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            part.write(fileName);
            downloadLinks += "<a href='http://10.0.3.108/download?file=" + name + "'>下载" + name.substring(0, name.lastIndexOf(".")) + "</a><br>";
            message += "<p>" + name + "上传成功</p>";
        }
        String html = "<html><body>";
        html += message;
        html += "<p>下载地址如下：</p>";
        html += downloadLinks;
        html += "</body></html>";
        resp.getWriter().write(html);
        System.out.println(req.getRemoteAddr());
        System.out.println(req.getLocalAddr());
        System.out.println(req.getRemoteHost());
    }
}
